from flask import Flask, request, jsonify, Response
import requests
import json
from flask_cors import CORS

app = Flask(__name__)
CORS(app)  # 自动处理 CORS，包括 OPTIONS

# 代理目标域名
TARGET_URL = "http://task.adszs.com"
API_KEY = "17400a82-e1bd-4af8-86b4-11a8ec2e9e70"


@app.before_request
def log_request_info():
    print(f"\n{'='*50}")
    print(f"METHOD   : {request.method}")
    print(f"PATH     : {request.path}")
    print(f"FULL PATH: {request.full_path if request.query_string else request.path}")

    if request.args:
        print(f"QUERY    : {dict(request.args)}")
    else:
        print(f"QUERY    : (empty)")

    headers = dict(request.headers)
    print(f"HEADERS  : {json.dumps(headers, indent=2)}")

    if request.is_json:
        try:
            json_data = request.get_json()
            print(f"JSON     : {json.dumps(json_data, indent=2)}")
        except:
            print(f"JSON     : <invalid JSON>")
    else:
        raw_data = request.get_data()
        if raw_data:
            try:
                decoded = raw_data.decode('utf-8')
                print(f"BODY     : {decoded}")
            except:
                print(f"BODY     : <binary or undecodable data, length={len(raw_data)}>")

    print(f"{'='*50}")


@app.route('/', defaults={'path': ''}, methods=['GET', 'POST', 'PUT', 'DELETE', 'PATCH', 'HEAD', 'OPTIONS'])
@app.route('/<path:path>', methods=['GET', 'POST', 'PUT', 'DELETE', 'PATCH', 'HEAD', 'OPTIONS'])
def proxy(path):
    target_url = f"{TARGET_URL}/{path}"
    if request.query_string:
        target_url += f"?{request.query_string.decode('utf-8')}"

    headers = dict(request.headers)
    headers['apikey'] = API_KEY
    headers.pop('Host', None)

    try:
        resp = requests.request(
            method=request.method,
            url=target_url,
            headers=headers,
            data=request.get_data(),
            cookies=request.cookies,
            allow_redirects=False,
            timeout=30
        )

        print(f"\n➡️  RESPONSE from {target_url}")
        print(f"STATUS CODE: {resp.status_code}")

        # 尝试解析 JSON 响应
        try:
            json_data = resp.json()
            print(f"RESPONSE JSON: {json.dumps(json_data, indent=2)}")
        except json.JSONDecodeError:
            # 如果不是 JSON，尝试返回文本摘要
            text_preview = resp.text[:500] if resp.text else '<empty>'
            print(f"RESPONSE (not JSON): {text_preview}")
            json_data = {
                "error": "Backend response is not JSON",
                "status_code": resp.status_code,
                "content_type": resp.headers.get('Content-Type', 'unknown'),
                "body_preview": text_preview
            }

        # 统一返回 JSON 格式
        return jsonify(json_data), resp.status_code

    except requests.exceptions.RequestException as e:
        error_msg = f"Request failed: {str(e)}"
        print(error_msg)
        return jsonify({
            "error": "Proxy request failed",
            "message": str(e)
        }), 502


if __name__ == '__main__':
    print("🚀 Proxy server running on http://localhost:9000")
    app.run(host='0.0.0.0', port=80, debug=True)